<template>
    <div class="app-container">
        <div class="customTab">
            <el-tabs type="border-card" v-model="activeTab" @tab-click="handleTabChange" v-loading="loading">
                <el-tab-pane label="总览统计" name="all">
                    
                    <!-- 筛选区域 -->
                    <el-form :model="chartQuery" ref="chartForm" :inline="true" class="search-form-new"
                        label-width="80px">
                        <el-form-item label="推广名称" prop="inviteCode">
                            <el-select v-model="chartQuery.inviteCode" clearable filterable placeholder="请选择推广名称">
                                <el-option v-for="item in promotionOptions" :key="item.inviteCode"
                                    :label="item.inviteName+'('+item.inviteCode+')'" :value="item.inviteCode" />
                            </el-select>
                        </el-form-item>
                        <el-form-item label="时间段" prop="dateRange">
                            <el-date-picker v-model="chartDateRange" type="daterange" range-separator="至"
                                start-placeholder="开始日期" end-placeholder="结束日期" value-format="yyyy-MM-dd" />
                        </el-form-item>
                        <el-form-item class="btns">
                            <el-button type="primary" icon="el-icon-search" @click="searchChart">搜索</el-button>
                            <el-button type="warning" icon="el-icon-refresh" @click="resetChartQuery">重置</el-button>
                        </el-form-item>
                    </el-form>
                    <el-row :gutter="20" style="margin-top: 20px;">
                        <el-col :span="10">
                    <!-- 漏斗图 -->
                            <FunnelChart :data="funnelData" width="100%" height="500px" />
                        </el-col>
                        <el-col :span="14">
                    <!-- 折线图 -->
                            <LineChart :key="chartRenderKey" style="width: 100%;" :x-axis-data="lineChartXAxis" :series-data="lineChartSeries"
                                height="500px" />
                        </el-col>
                    </el-row>
                </el-tab-pane>
                <el-tab-pane label="用户统计" name="statistics">
                    <!-- 筛选区域 -->
                    <el-form :model="queryParams" ref="queryForm" :inline="true" class="search-form-new"
                        label-width="80px">
                        <el-form-item label-width="60px" label="用户名" prop="userName">
                            <el-input v-model="queryParams.userName" placeholder="请输入用户名" clearable />
                        </el-form-item>
                        <!-- <el-form-item label-width="60px" label="用户名" prop="customerId">
                            <el-select class="bumen" collapse-tags filterable clearable v-model="queryParams.customerId"
                                placeholder="请选择用户名">
                                <el-option v-for="(item, key) in userOptions" :key="key" :label="item.nickName"
                                    :value="item.userId" />
                            </el-select>
                        </el-form-item> -->
                        <el-form-item label="推广名称" prop="inviteCode">
                            <el-select v-model="queryParams.inviteCode" clearable filterable placeholder="请选择推广名称">
                                <el-option v-for="item in promotionOptions" :key="item.inviteCode" :label="item.inviteName +'('+item.inviteCode+')'" :value="item.inviteCode" 
                                    />
                            </el-select>
                        </el-form-item>
                        <el-form-item class="btns">
                            <el-button type="primary" icon="el-icon-search" @click="search">搜索</el-button>
                            <el-button type="warning" icon="el-icon-refresh" @click="resetQuery">重置</el-button>
                        </el-form-item>
                    </el-form>

                    <!-- 表格 -->
                    <div class="table_box table_box_new">
                        <el-table :data="tableData.records" border stripe v-loading="loading">
                            <el-table-column align="center" prop="userName" label="用户名" min-width="120" />
                            <el-table-column align="center" prop="inviteName" label="推广名称" min-width="120" />
                             <el-table-column align="center" prop="inviteCode" label="推广码" min-width="120" />
                            <el-table-column align="center" prop="registerTime" label="注册时间" min-width="160" />
                            <el-table-column align="center" prop="consultTime" label="咨询时间" min-width="160" />
                            <el-table-column align="center" prop="payTime" label="支付时间" min-width="160" />
                        </el-table>
                    </div>

                    <div >
                        <pagination v-show="tableData.total > 0" :total="tableData.total"
                            :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize" @pagination="getList" />
                    </div>
                </el-tab-pane>
            </el-tabs>
        </div>
    </div>
</template>

<script>
import FunnelChart from './charts/FunnelChart.vue';
import LineChart from './charts/LineChart.vue';
import { stats, dayStats, noPage, userList } from "@/api/shopTuig/index";
import supplyConfigApi from "@/api/system/supplyConfig";
export default {
  name: "Promotion",
    components: {
        FunnelChart,
        LineChart
    },
  data() {
    return {
      activeTab: 'all',
      loading: false,
      
      // 表格数据
            queryParams: { username: '', inviteCode: '', pageNum: 1, pageSize: 10 },
      tableData: { records: [], total: 0 },
      
      // 图表数据
            chartQuery: { inviteCode: '', pageNum: 1, pageSize: 10 },
      chartDateRange: [],
      promotionOptions: [],
      userOptions: [],
      
            // 漏斗图数据
            funnelData: [

            ],

            // 折线图数据
            lineChartXAxis: ['1月', '2月', '3月', '4月', '5月', '6月', '7月'],
            lineChartSeries: [

            ]
            ,
            // 折线图强制重渲染key
            chartRenderKey: 0
    };
  },
  mounted() {
        // 设置默认查询最近一个月的数据
        this.setDefaultDateRange();
        this.loadChartData();
    this.getPromotionOptions();
  },
  methods: {
    handleTabChange(tab) {
            // 切换标签页时的处理逻辑
            console.log(tab.name, 888)
            if (tab.name == 'statistics') {
                if (this.userOptions.length == 0) {
                    this.getUserOptions();
                }
                this.getList()
            } else {
                this.searchChart()
      }
    },
    
    // 表格相关方法
    getList() {
      this.loading = true;
            userList(this.queryParams).then(res => {
                this.tableData = { records: res.rows, total: res.total };
            })
        this.loading = false;
    },
    search() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    resetQuery() {
      this.$refs.queryForm.resetFields();
      this.queryParams.pageNum = 1;
      this.getList();
    },
    
        // 筛选项
    getPromotionOptions() {
            noPage().then(res => {
                this.promotionOptions = res.rows
            })

    },
    getUserOptions() {
            supplyConfigApi
                .getAllUserList({
                    userNewType: 1,
                })
                .then((res) => {
                    this.userOptions = res.rows || [];
                });
    },
    searchChart() {
            // 搜索图表数据
            this.loadChartData();
    },
    resetChartQuery() {
      this.$refs.chartForm.resetFields();
    //   this.chartDateRange = [];
    this.setDefaultDateRange()
      this.loadChartData();
        },

        // 设置默认日期范围（最近一个月）
        setDefaultDateRange() {
            const endDate = new Date();
            const startDate = new Date();
            startDate.setMonth(startDate.getMonth() - 1);

            this.chartDateRange = [
                this.formatDate(startDate),
                this.formatDate(endDate)
            ];
        },

        // 格式化日期为 YYYY-MM-DD
        formatDate(date) {
            const year = date.getFullYear();
            const month = String(date.getMonth() + 1).padStart(2, '0');
            const day = String(date.getDate()).padStart(2, '0');
            return `${year}-${month}-${day}`;
        },

        // 加载图表数据
        loadChartData() {
            this.loading = true;

            // 构建查询参数
            // const queryParams = {
            //     ...this.chartQuery,
            //     startDate: this.chartDateRange && this.chartDateRange[0] ? this.chartDateRange[0] : '',
            //     endDate: this.chartDateRange && this.chartDateRange[1] ? this.chartDateRange[1] : ''
            // };

             this.chartQuery = this.addDateRange(this.chartQuery, this.chartDateRange)
            stats(this.chartQuery).then(res => {
                if (res.code === 200 && res.data) {
                    // 处理漏斗图数据
                    this.processFunnelData(res.data);

                }
                this.loading = false;
            }).catch(error => {
                this.loading = false;
            });
            dayStats(this.chartQuery).then(res => {
                if (res.code === 200 && res.data) {
                    // 处理折线图数据
                    this.processLineChartData(res.data);
                }
                this.loading = false;
            }).catch(error => {
                this.loading = false;
            });


        },

        // 处理漏斗图数据
        processFunnelData(data) {
            console.log('处理漏斗图数据:', data);

            // 根据接口返回的数据结构处理 
            const behaviorMap = {
                1: { name: '点击', },
                2: { name: '下载', },
                3: { name: '安装', },
                4: { name: '注册', },
                5: { name: '咨询', },
                6: { name: '支付', }
            };

            // 按行为类型分组统计
            const behaviorStats = {};
            data.forEach(item => {
                if (!behaviorStats[item.behavior]) {
                    behaviorStats[item.behavior] = 0;
                }
                behaviorStats[item.behavior] += item.number;
            });

            console.log('行为统计:', behaviorStats);


            // 构建漏斗图数据
            const funnelData = [];
            const behaviors = [1, 2, 3, 4, 5, 6]; // 按顺序处理：点击→下载→安装→注册→咨询→支付
            let previousValue = 0;

            behaviors.forEach((behavior, index) => {
                const value = behaviorStats[behavior] || 0;
                const behaviorInfo = behaviorMap[behavior];
                // 计算转化率（相对于前一个阶段）
                let conversionRate = '';
                if (index > 0 && previousValue > 0) {
                    conversionRate = ((value / previousValue) * 100).toFixed(2) + '%';
                }

                funnelData.push({
                    number: value,
                    name: behaviorInfo.name + '率',
                    oriname: behaviorInfo.name,
                });
                previousValue = value;
            });


            this.funnelData = funnelData;
        },

        // 处理折线图数据
        processLineChartData(data) {
            console.log('处理折线图数据:', data);

            // 接口数据格式: { "2025-09-18": [{number: 1, statsDay: "2025-09-18", id: 10, behavior: 1}, ...], "2025-09-19": [...] }
            // 按日期分组统计
            const dateStats = {};

            // 遍历接口返回的日期数据
            Object.keys(data).forEach(date => {
                const dayData = data[date];
                if (Array.isArray(dayData)) {
                    dayData.forEach(item => {
                        if (!dateStats[date]) {
                            dateStats[date] = {};
                        }
                        if (!dateStats[date][item.behavior]) {
                            dateStats[date][item.behavior] = 0;
                        }
                        dateStats[date][item.behavior] += item.number;
                    });
                }
            });

            // 生成完整的日期范围（从开始日期到结束日期）
            const allDates = this.generateDateRange();
            this.lineChartXAxis = allDates;

            // 构建各行为的数据系列
            const behaviorNames = ['点击', '下载', '安装', '注册', '咨询', '支付'];
            const behaviorColors = ['#4CAF50', '#2196F3', '#FF9800', '#F44336', '#73c0de', '#9C27B0'];

            this.lineChartSeries = behaviorNames.map((name, index) => {
                const behavior = index + 1; // behavior从1开始
                const seriesData = allDates.map(date => {
                    return dateStats[date] && dateStats[date][behavior] ? dateStats[date][behavior] : 0;
                });

                return {
                    name: name,
                    data: seriesData,
                    color: behaviorColors[index]
                };
            });

            // 数据就绪后强制触发折线图重渲染
            this.chartRenderKey++;

        },

        // 生成完整的日期范围（从开始日期到结束日期）
        generateDateRange() {
            const dates = [];

            // 获取查询的日期范围
            const startDate = this.chartDateRange && this.chartDateRange[0] ? new Date(this.chartDateRange[0]) : new Date();
            const endDate = this.chartDateRange && this.chartDateRange[1] ? new Date(this.chartDateRange[1]) : new Date();

            // 如果没有设置日期范围，默认显示最近7天
            if (!this.chartDateRange || this.chartDateRange.length === 0) {
                const today = new Date();
                for (let i = 6; i >= 0; i--) {
                    const date = new Date(today);
                    date.setDate(date.getDate() - i);
                    dates.push(this.formatDate(date));
                }
                return dates;
            }

            // 生成从开始日期到结束日期的所有日期
            const currentDate = new Date(startDate);
            while (currentDate <= endDate) {
                dates.push(this.formatDate(currentDate));
                currentDate.setDate(currentDate.getDate() + 1);
            }

            return dates;
        },

        // 生成默认日期（当没有数据时）
        generateDefaultDates() {
            const dates = [];
            const today = new Date();
            for (let i = 6; i >= 0; i--) {
                const date = new Date(today);
                date.setDate(date.getDate() - i);
                dates.push(this.formatDate(date));
            }
            return dates;
        },


  }
}
</script>

<style lang="scss" scoped>
.chart-container {
  margin: 20px 0;
  padding: 20px;
    background: #fff;
    border-radius: 8px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.chart-title {
  font-size: 16px;
  font-weight: 500;
  margin-bottom: 15px;
  color: #333;
    text-align: center;
}

.pages-box {
  margin-top: 20px;
  text-align: center;
}
</style>